import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import './LogViewer.css';

const LogViewer = ({ taskCode, trainCode }) => {
  const [logLines, setLogLines] = useState([]);
  const [trainLogIndex, setTrainLogIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [autoScroll, setAutoScroll] = useState(true);
  const logContainerRef = useRef(null);

  const fetchTrainLog = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:8000/train/getTrainLog', {
        params: {
          task_code: taskCode,
          train_code: trainCode,
          train_log_index: trainLogIndex
        }
      });

      if (response.data.code === 200) {
        const newLogLines = response.data.data.log_lines;
        setLogLines(prevLines => [...prevLines, ...newLogLines]);
        setTrainLogIndex(response.data.data.train_log_index);
      } else {
        setError(`获取日志失败: ${response.data.message}`);
      }
    } catch (err) {
      setError(`请求错误: ${err.message}`);
      console.error('Error fetching train logs:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setLogLines([]);
    setTrainLogIndex(0);
    setError(null);
    
    fetchTrainLog();
    
    const intervalId = setInterval(fetchTrainLog, 6000);
    
    return () => clearInterval(intervalId);
  }, [taskCode, trainCode]);

  useEffect(() => {
    if (autoScroll && logContainerRef.current) {
      logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight;
    }
  }, [logLines, autoScroll]);

  const handleScroll = () => {
    if (logContainerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current;
      if (scrollHeight - scrollTop - clientHeight < 50) {
        setAutoScroll(true);
      } else {
        setAutoScroll(false);
      }
    }
  };

  return (
    <div className="log-viewer">
      <h2>训练日志 - {taskCode}/{trainCode}</h2>
      <div className="log-controls">
        <button 
          onClick={() => setAutoScroll(!autoScroll)}
          className={autoScroll ? 'active' : ''}
        >
          {autoScroll ? '自动滚动: 开' : '自动滚动: 关'}
        </button>
        <button onClick={fetchTrainLog} disabled={loading}>
          {loading ? '加载中...' : '刷新日志'}
        </button>
      </div>
      
      {error && <div className="error-message">{error}</div>}
      
      <div 
        className="log-container" 
        ref={logContainerRef}
        onScroll={handleScroll}
      >
        {logLines.length === 0 ? (
          <p className="no-logs">暂无日志数据</p>
        ) : (
          <pre className="log-content">
            {logLines.join('')}
          </pre>
        )}
      </div>
    </div>
  );
};

export default LogViewer;